package com.rock.code.province.tj.busi.socketdr;

import java.io.*;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;

public class Client {
    private Socket socket = null;
    private OutputStream os = null;
    private InputStream is = null;
    WriterAndReadFile writerFile = new WriterAndReadFile();
    SocketUtil socketUtil = new SocketUtil();
    Logger logger = Logger.getLogger("Client");
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

    public static void main(String[] args) {
        new Client().new SocketThread().start();
    }


    /**
     * 发送心跳包
     */
    public void sendHeartbeat() {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            String heart = "Send heartbeat packe";
                            Thread.sleep(10 * 1000);// 10s发送一次心跳
                            os.write(heart.getBytes());
                            os.flush();
                            logger.info(heart);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class SocketThread extends Thread {

        @Override
        public void run() {
            long startTime = System.currentTimeMillis();
            long endTime = 0;
//            sendHeartbeat();
            while (true) {
                try {
                    if (socket == null || socket.isClosed()) {
                        socket = new Socket("172.16.100.42", 18382); // 连接socket
//                        socket = new Socket("192.168.43.52", 8080); // 连接socket
                        logger.info(">>>>>>>>>>>开始连接时间：" + df.format(new Date()));
                        try {
                            socket.sendUrgentData(0xFF);
                        } catch (Exception e) {
                            logger.info(">>>>>>>>>>>客户端异常,断开连接时间：" + df.format(new Date()));
                            socket.close();
                            socket = null;
                            e.printStackTrace();
                            continue;
                        }
                        os = socket.getOutputStream();
                        //发送请求
//                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                        String jsonParams = "{\"servicecode\":\"P01_02001\",\"source\":\"YT\"}";
                        //向服务器端发送一条消息
//                        bw.write(jsonParams + "\n");
//                        bw.flush();
                        socketUtil.sendRequest(jsonParams, os);
                        logger.info(">>>>>>>>>>>>客户端发送请求!<<<<<<<<<<<<<<<<<<<<");
                        //启动心跳包
                        sendHeartbeat();
                    }
                    Thread.sleep(100);
                    //获取服务器返回数据
                    is = socket.getInputStream();
                    int size = is.available();
                    if (size <= 0) {
                        if ((System.currentTimeMillis() - startTime) > 3 * 6 * 10 * 1000) { // 如果超过60秒没有收到服务器发回来的信息，说明socket连接可能已经被远程服务器关闭
                            socket.close(); // 这时候可以关闭socket连接
                            endTime = System.currentTimeMillis();
                            logger.info("断开连接,服务器超时时间：" + (endTime - startTime));
                        }
                        continue;
                    } else {
                        startTime = System.currentTimeMillis();
                    }
                    BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String mess = br.readLine();
                    logger.info(">>>>>>>>>>>>>>>>>>服务器响应数据<<<<<<<<<<<<<<<<<<<<:" + "\n" + mess);
                    //给服务端返回
                    boolean result = writerFile.writeFileStr(mess, "socketout.txt");
                    if (result == true) {
                        //发送成功应答
                        String sucess = "Message received successfully";
                        os.write(sucess.getBytes());
                        os.flush();
                        logger.info(">>>>>>>>>>>>>>>>处理服务器数据完毕<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    try {
                        socket.close();
                        is.close();
                        os.close();
                        is = null;
                        os = null;
                        socket = null;
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }
}

